package dongze.com.ckdj.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Camera;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;

import java.util.Arrays;
import java.util.Collections;
import java.util.regex.Pattern;

import dongze.com.ckdj.util.MyLog;
import me.dm7.barcodescanner.zxing.ZXingScannerView;

/**
 * Created by fanqwz on 2017/7/21.
 */

public class QRScannerActivity extends BaseActivity implements ZXingScannerView.ResultHandler {
    private static final String TAG = QRScannerActivity.class.getSimpleName();
    private static final int CAMERA_PERMISSION_REQUEST_CODE = 1025;
    private ZXingScannerView mScannerView;
    private Pattern mRegularExpression;

    @Override
    public void onCreate(Bundle state) {
        MyLog.d(TAG, "onCreate: " + this);
        super.onCreate(state);
        mScannerView = new ZXingScannerView(this);   // Programmatically initialize the scanner view
//        mScannerView.setAutoFocus(true);
//        mScannerView.setFlash(true);
        setContentView(mScannerView);                // Set the scanner view as the content view

        Intent intent = getIntent();
        String format = intent.getStringExtra("format");
        String regular = intent.getStringExtra("regular");

        if (format != null) {
            mScannerView.setFormats(Arrays.asList(new BarcodeFormat[]{BarcodeFormat.valueOf(format)}));
        }

        if (regular != null && !regular.isEmpty()) {
            mRegularExpression = Pattern.compile(regular);
        }
    }

    @Override
    public void onResume() {
        MyLog.d(TAG, "onResume: " + this);
        super.onResume();
        mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.

        if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                mScannerView.startCamera();          // Start camera on resume
            } else {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
            }
        } else {
            mScannerView.startCamera();          // Start camera on resume
        }
    }

    @Override
    public void onPause() {
        MyLog.d(TAG, "onPause: " + this);
        super.onPause();
        mScannerView.stopCamera();           // Stop camera on pause
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            if (permissions.length > 0 && permissions[0].equals(Manifest.permission.CAMERA) && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                mScannerView.startCamera();
            } else {
                Toast.makeText(this, "no permission to access camera!", Toast.LENGTH_SHORT).show();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void handleResult(Result result) {
        // Do something with the result here
        MyLog.v(TAG, result.getText()); // Prints scan results
        MyLog.v(TAG, result.getBarcodeFormat().toString()); // Prints the scan format (qrcode, pdf417 etc.)

        try {
            if (mRegularExpression == null
                    || (mRegularExpression != null && mRegularExpression.matcher(result.getText()).matches())) {
                Intent intent = new Intent();
                intent.putExtra("format", result.getBarcodeFormat().toString());
                intent.putExtra("code", result.getText());
                setResult(RESULT_OK, intent);
                finish();
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // If you would like to resume scanning, call this method below:
        mScannerView.resumeCameraPreview(this);
    }
}
